<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="接收人" prop="assigneerId">
        <el-select v-model="formData.assigneerId" filterable clearable placeholder="请选择复检人" style="width: 100%;">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
        </el-select>
      </el-form-item>
      <!-- 
      <el-form-item label="复检人" prop="assigneerIds">
        <el-select clearable multiple filterable v-model="formData.assigneerIds" placeholder="请选择复检人">
          <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
        </el-select>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { RecheckTobeApi } from '@/api/mold/rechecktobe'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false)
const dialogTitle = ref('派工')
const formLoading = ref(false) // 表单的加载中
const formData = ref({
  id: undefined, // 复检任务ID
  assigneerId: undefined, // 复检人ID
  assigneerIds: []
})
const formRules = reactive({
  assigneerId: [{ required: true, message: '请选择复检人', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const userList = ref<UserVO[]>([]) // 复检人列表

/** 获取复检人列表 */
const getUserList = async () => {
  try {
    userList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    message.error('获取复检人列表失败')
    console.error(error)
  }
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  console.log('id', id)
  formData.value.id = id
  await getUserList()
  resetForm()
  // 确保在DOM更新后重置表单元素的状态
  nextTick(() => {
    formData.value.assigneerId = undefined
  })
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {

  console.log('formData.value', formData.value)

  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 调用派工接口，提交任务ID和用户ID
    await RecheckTobeApi.dispatchRecheckTobe(formData.value.id, formData.value.assigneerId)
    message.success('派工成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (error) {
    console.error(error)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value.assigneerId = undefined
  formData.value.assigneerIds = []
  formRef.value?.resetFields()
}
</script>